<template>
	<view :class="themeName">
		<!-- #ifndef  H5 -->
		<!-- <custom-navbar is-back title="订单支付" ></custom-navbar> -->
		<!-- #endif -->
		<view class="payment u-skeleton">
			<!-- Header -->
			<view class="payment-header">
				<price class="u-skeleton-fillet" :content="amount" mainSize="56rpx" minorSize="40rpx" color="#FFFFFF" />
				<template v-if="timeout > 0">
					<view class="payment-count-down">
						<text>支付剩余时间</text>
						<u-count-down :timestamp="timeout" :show-days="false" :show-hours="false" :font-size="22" />
					</view>
				</template>
			</view>

			<!-- Main -->
			<view class="payment-main">
				<view class="payway-container u-skeleton-fillet">
					<!-- Payway -->
					<u-radio-group v-model="payway" style="width: 100%">
						<view class="payway">
							<view class="payway-item" v-for="(item, index) in paywayList" :key="item.id"
								@click="changePayway(item)">
								<u-image :src="item.icon" width="48" height="48" mode="scaleToFill" />
								<view class="payway-item-content">
									<text class="payway-item-content-name">{{ item.name }}</text>
									<text class="payway-item-content-tips">{{ item.extra }}</text>
								</view>
								<u-radio shape="circle" :name="item.pay_way" :active-color="themeColor" />
							</view>
						</view>
					</u-radio-group>
					<template v-if="!paywayList.length">
						<view class="payway-empty">暂无支付方式</view>
					</template>
				</view>
			</view>

			<!-- Footer -->
			<view class="payment-footer" v-if="paywayList.length">
				<view :class="[
                        'payment-submit',
                        'u-skeleton-fillet',
                        { 'payment-submit--disabled': loadingPay }
                    ]" @tap="handlePrepay" class="footer">
					<u-loading mode="circle" :show="loadingPay" />
					<text v-show="!loadingPay">立即支付</text>
				</view>
			</view>

			<!-- 页面状态 -->
			<page-status :status="pageStatus">
				<template #error>
					<u-empty :text="pageErrorMsg" src="/static/images/empty/order.png" :icon-size="280" />
				</template>
			</page-status>
			<u-popup v-model="Alipayshow" mode="bottom" height="900rpx" safe-area-inset-bottom border-radius="20"
				closeable @close="handleclose">
				<view class="Alipay">
					<view class="m-t-50">
						<price class="u-skeleton-fillet" :content="amount" mainSize="56rpx" minorSize="40rpx" />
					</view>
					<view class="flex row-between m-t-50" style="width: 100%">
						<text class="bold">支付方式</text>
						<text class="bold">{{ paywayText }}</text>
					</view>

					<view v-if="qrCodeImg">
						<image style="width:200rpx; height: 200rpx;" :src="qrCodeImg" mode="widthFix"
							:show-menu-by-longpress="true"></image>
					</view>

					<view class="p-20 m-t-50 m-b-50" style="width: 100%; background-color: #f7f7f7">
						<view>1.打开微信或者支付宝客户端，扫一扫</view>
						<view>2.长按二维码保存图片，然后打开 {{paywayText}} 客户端，通过扫一扫功能，从相册里选择所保存的图片</view>
						<!-- <view>3.{{ paywayTip }}</view> -->
						<!-- 请复制链接,粘贴至浏览器并支付. -->
						<!-- 请复制链接,在微信客户端打开 -->
					</view>

					<!-- <button class="btn" @click="$copy(key)">复制链接</button> -->

					<!-- <button class="btn m-t-20" @click="savaQrcode">点击保存二维码</button> -->

					<button class="btn m-t-20" @click="savaQrImg">
						<!-- #ifndef H5 -->
						保存图片到相册
						<!-- #endif -->
						<!-- #ifdef H5 -->
						长按保存图片到相册
						<!-- #endif -->
					</button>

					<!-- <button class="btn m-t-20" @click="queryPayStatus">已支付，查询支付结果</button> -->

				</view>
			</u-popup>
		</view>

		<u-skeleton :loading="loadingSkeleton" :animation="true" bgColor="#FFFFFF" />
	</view>
</template>

<script>
	/**
	 * @description 支付页面
	 * @query {String} from 订单来源: order-商品订单; recharge-充值订单;
	 * @query {Number} order_id	订单ID
	 */
	import {
		mapGetters
	} from 'vuex'
	import {
		apiPrepay,
		apiPayway,
		apiPayStatus
	} from '@/api/app'
	import {
		wxpay,
		alipay,
		ttpay
	} from '@/utils/pay'
	import {
		PaymentStatusEnum,
		PayWayEnum,
		PageStatusEnum
	} from '@/utils/enum'
	import store from '@/store'
	let queryTimer = null

	function pollCode(fn, interval, timeout = 600000) {
		var endTime = Number(new Date()) + (timeout || 600000);
		interval = interval || 1000;
		var checkCondition = function(resolve, reject) {
			// 如果超时则停止轮询
			if (Number(new Date()) > endTime) {
				reject(new Error("轮询超时"));
				// 如果条件满足则停止轮询
			} else if (fn()) {

				console.log("已经拿到了条件")
				resolve();
				// 否则继续轮询
			} else {
				console.log("abcd继续轮询")
				clearTimeout(queryTimer)
				queryTimer = setTimeout(checkCondition, interval, resolve, reject);
			}
		};
		return new Promise(checkCondition);
	}
	export default {
		name: 'Payment',

		data() {
			return {
				from: '', // 订单来源
				order_id: '', // 订单ID
				amount: 0, // 支付金额
				timeout: 0, // 倒计时间戳
				payway: '', // 支付方式
				paywayText: '',
				paywayTip: '',
				paywayList: [], // 支付方式列表
				Alipayshow: false,
				pageStatus: PageStatusEnum['NORMAL'],
				pageErrorMsg: '',
				loadingSkeleton: true, // 骨架屏Loading
				loadingPay: false, // 支付处理中Loading
				key: '',
				qrCodeImg: '',
				queryTimer: null, // 定时器
				fyPlayStatus: ''
			}
		},
		mounted() {
			const vm = this

			this.$nextTick(() => {
				setTimeout(() => {
					// vm.savaQrcode()
				})

			})
		},
		methods: {
			plusDownloadImg(opts) {
				// #ifdef APP-PLUS
				const url = this.qrCodeImg
				let fileName = 'downloaded-image.jpg'
				const token = store.getters.token
				if (url) {
					let dtask = plus.downloader.createDownload(url, {
						filename: '_downloads/' + fileName
					}, (d, status) => {
						if (status === 200) {
							console.log('下载成功：' + d.filename);
							// 需要转换成绝对路径
							let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
							this.plusSaveImg(fileSaveUrl);
						} else {
							this.$showToast.error('下载失败');
							console.log('下载失败：' + status);
						}
					});
					dtask.setRequestHeader('token', token);
					dtask.start();
				}
				// #endif
			},

			/**
			 * 浏览器的图片保存方案, 暂时没有相关需求。先放这里
			 */
			saveBrowserImageToPhotosAlbum() {
				// 创建一个Canvas元素
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');

				// 设置Canvas的大小
				canvas.width = 600;
				canvas.height = 400;

				// 绘制一些图形或者文字到Canvas上
				ctx.fillStyle = '#FF0000'; // 设置填充颜色
				ctx.fillRect(0, 0, 600, 400); // 绘制一个红色的矩形

				// 将Canvas转换为图片
				var dataURL = canvas.toDataURL('image/png');

				// 创建一个Image元素
				var img = new Image();
				img.src = this.qrCodeImg;

				// 将Image元素添加到DOM中（可选，用于展示图片）
				document.body.appendChild(img);

				// 创建一个链接元素用于下载图片
				var link = document.createElement('a');
				link.download = 'downloaded-image.png';
				link.href = this.qrCodeImg;;
				link.click();
			},

			savaQrImg() {
				// #ifdef H5
				uni.showToast({
					title: "请长按图片保存",
				});
				// #endif

				// #ifndef H5
				const vm = this
				uni.saveImageToPhotosAlbum({
					filePath: vm.qrCodeImg,
					success: function(res) {
						uni.showToast({
							title: '保存成功'
						})
					},
					fail: (err) => {
						uni.showToast({
							title: '保存失败',
							icon: 'error'
						})
					}
				});
				// #endif

			},
			/**
			 * 通过一个二维码，然后将二维码转换成, 这是以前的需求。
			 */
			savaQrcode() {

				// #ifdef H5
				this.$toast({
					title: "请长按图片保存",
				});
				// #endif

				// #ifndef  H5
				const vm = this
				this.$refs.painter.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {
						// 非H5 保存到相册
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function() {
								console.log("到哪里")
								uni.showToast({
									title: '保存成功'
								})
							},
							fail: (err) => {
								console.log("saveImageToPhotosAlbum fail", err)
								uni.showToast({
									title: '保存失败',
									icon: 'error'
								})
							}
						});

					},
					fail: (err) => {
						console.log("canvasToTempFilePathSync err", err)
					}
				});
				// #endif
			},
			// 更改支付方式
			changePayway(row) {
				// remark
				this.paywayText = row.name
				this.$set(this, 'payway', row.pay_way)
			},

			// 初始化页面数据
			initPageData() {
				// 获取支付方式
				return new Promise((resolve, reject) => {
					apiPayway({
							from: this.from,
							order_id: this.order_id
						})
						.then((data) => {
							this.amount = data.order_amount
							this.paywayList = data.lists
							this.payway = this.paywayList[0]?.pay_way
							// 倒计时
							const startTimestamp = new Date().getTime() / 1000
							const endTimestamp = data.cancel_time * 1
							this.timeout = endTimestamp - startTimestamp
							resolve(data)
						})
						.catch((errMsg) => reject(errMsg))
				})
			},
			//支付宝弹窗关闭
			handleclose() {
				this.queryPayResult()
					.then((result) => {
						result
							?
							this.handlePayResult(PaymentStatusEnum['SUCCESS']) :
							this.handlePayResult(PaymentStatusEnum['FAIL'])
					})
					.catch((errMsg) => this.handlePayResult(PaymentStatusEnum['FAIL']))
				this.loadingPay = false
			},
			// 预支付处理
			handlePrepay() {
				if (this.userInfo.is_auth === 0 && this.payway == PayWayEnum['WECHAT']) {
					uni.showModal({
						content: '当前账号未微信授权，请前往个人设置授权',
						confirmColor: this.themeColor,
						confirmText: '前往授权',
						success: ({
							confirm
						}) => {
							if (confirm) {
								this.$Router.push({
									path: '/bundle/pages/user_profile/user_profile',
									query: {
										form: 'payment'
									}
								})
							}
						}
					})
					return
				}

				this.key =
					`${store.getters.appConfig.domain}/mobile/bundle/pages/toAlipay/toAlipay?id=${this.order_id}&from=${this.from}&pay_way=${this.payway}&key=${store.getters.token}`
				// 阻止重复操作
				if (this.loadingPay) return
				this.loadingPay = true
				// WALLET: 1, // 钱包
				// WECHAT: 2, // 微信
				// ALIPAY: 3, // 支付宝
				// TOUTIAO: 4, // 头要
				// DOWMLINE: 5 ,//线下支付
				// FY_WECHAT: 6, //  富友微信
				// FY_ALIPAY: 7, // 富友支付宝
				// 处理：支付
				const callback = ['', '']
				this.qrCodeImg = ''
				this.fyPlayStatus = ''
				clearTimeout(this.queryTimer)

				apiPrepay({
						from: this.from,
						order_id: this.order_id,
						pay_way: this.payway
					})
					.then(async ({
						config,
						pay_way
					}) => {
						console.log("config, pay_way", config)
						console.log("pay_way", pay_way)
						switch (+pay_way) {
							// 钱包 1
							case PayWayEnum['WALLET']:
								await this.handleWalletPay()
								break
								// 线下支付 5
							case PayWayEnum['DOWMLINE']:
								await this.handleDownLinePay()
								break
								//   微信 2
							case PayWayEnum['WECHAT']:
								this.Alipayshow = true
								await this.handleWechatPay(config)
								break
								// 支付宝 3 PayWayEnum['ALIPAY']
							case PayWayEnum['ALIPAY']:
								//TODO

								uni.$on('Alipay', () => {
									this.Alipayshow = true
								})
								await this.handleAlipayPay(
									config, {
										from: this.from,
										order_id: this.order_id,
										pay_way: pay_way
									},
									store.getters.token
								)
								break
								//  头条 4
							case PayWayEnum['TOUTIAO']:
								await this.handleTtPay(config)
								break;
								// FY_WECHAT 6 富友微信
							case PayWayEnum['FY_WECHAT']:
								this.qrCodeImg = config.qr_code
								this.key = config.order_info
								this.Alipayshow = true
								this.paywayTip = '请复制链接,在微信客户端打开'
								await this.handleFY()
								break;
								// FY_ALIPAY 7 富友支付宝
							case PayWayEnum['FY_ALIPAY']:
								console.log(" 富友支付宝")
								this.qrCodeImg = config.qr_code
								this.key = config.order_info
								this.Alipayshow = true
								this.paywayTip = '请复制链接,粘贴至浏览器并支付.'
								await this.handleFY()
								// await this.handleAlipayPay(
								//     config,
								//     {
								//         from: this.from,
								//         order_id: this.order_id,
								//         pay_way: pay_way
								//     },
								//     store.getters.token
								// )
								break;
							default:
								throw '支付异常'
						}
					})
					.then(() => {
						this.handlePayResult(PaymentStatusEnum['SUCCESS'])
					})
					.catch((errMsg) => {
						
						console.log('PAYMENT_ERROR_MSG:', errMsg)
						uni.showToast({
							title:errMsg,
							icon:'none'
						})
						setTimeout(()=>{
							this.handlePayResult(PaymentStatusEnum['FAIL'])
						},1500)
						
					})
					.finally(() => {
						this.loadingPay = false
					})
			},

			// 微信支付
			handleWechatPay(data) {
				return new Promise((resolve, reject) => {
					wxpay(data)
						.then(async (res) => {
							console.log("handleWechatPay", res)
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult()
									.then((result) => {
										result ? resolve(res) : reject(res)
									})
									.catch((errMsg) => reject(errMsg))
							})
							// #endif
						})
						.catch((errMsg) => {
							console.log('handleWechatPay error', errMsg)
							reject(errMsg)
						})
				})
			},

			// 支付宝支付
			handleAlipayPay(data, params, token) {
				return new Promise((resolve, reject) => {
					alipay(data, params, token)
						.then(async (res) => {
							// #ifndef H5
							resolve(res)
							// #endif

							// #ifdef H5
							this.$on('h5_payment', () => {
								this.queryPayResult()
									.then((result) => {
										result ? resolve(res) : reject(res)
									})
									.catch((errMsg) => reject(errMsg))
							})
							// #endif
						})
						.catch((errMsg) => {
							console.log('handleAlipayPay catch', errMsg)
							reject(errMsg)
						})
				})
			},

			// 钱包余额支付
			handleWalletPay() {
				return new Promise((resolve, reject) => {
					resolve('支付成功')
				})
			},
			// 线下支付
			handleDownLinePay() {
				return new Promise((resolve, reject) => {
					resolve('支付成功')
				})
			},
			// 头条支付
			handleTtPay(data) {
				return new Promise((resolve, reject) => {
					ttpay(data)
						.then(async (res) => {
							resolve(res)
						})
						.catch((errMsg) => reject(errMsg))
				})
			},

			// 富友支付宝,
			// @todo 这里应该需要优化下。
			handleFY() {
				const vm = this
				vm.fyPlayStatus = 'loading'
				clearTimeout(vm.queryTimer)
				return new Promise((resolve, reject) => {
					// resolve('支付成功')
					this.pollQrueryResult(resolve, reject).then((res) => {
						console.log("handleFY res", res)
					}).catch((err) => {
						console.log("handleFY err", err)
					})
				})
			},
			// 处理结果
			handlePayResult(result) {
				uni.$emit('duringPayment', {
					result,
					payway: this.payway,
					order_id: this.order_id
				})
			},
			queryPayStatus() {
				this.queryPayResult().then((result) => {
					if (!result) {
						uni.showToast({
							title: '该订单尚未支付'
						})
						return
					}
					uni.showToast({
						title: '支付成功'
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order_list/order_list?mode=pay'
						})
					}, 1000)
				}).catch(() => {
					uni.showToast({
						title: '该订单尚未支付，'
					})
				})
			},
			// 查询支付结果
			queryPayResult() {
				return new Promise((resolve, reject) => {
					apiPayStatus({
							from: this.from,
							order_id: this.order_id
						})
						.then((res) => {
							const {
								pay_status
							} = res
							console.log('pay_status', pay_status)

							resolve(!!pay_status)
						})
						.catch((errMsg) => reject(errMsg))
				})
			},
			pollQrueryResult(resolve, reject) {
				// resolve('支付成功')
				const vm = this
				if (vm.fyPlayStatus !== 'loading') {
					clearTimeout(vm.queryTimer)
					vm.queryTimer = null
					return Promise.reject({
						message: '未知原因取消支付'
					})
				}
				return this.queryPayResult().then((res) => {
					if (res) {
						uni.showToast({
							title: '已支付',
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/order_list/order_list?mode=pay'
							})
						}, 1000)
						console.log("pollQrueryResult 支付成功", res)
						vm.fyPlayStatus = 'success'
						vm.handlePayResult(PaymentStatusEnum['SUCCESS'])
						return resolve('支付成功')

					}
					console.log("pollQrueryResult 待支付", res)
					clearTimeout(vm.queryTimer)
					vm.queryTimer = setTimeout(() => {
						vm.pollQrueryResult(resolve, reject)
					}, 2000)

				}).catch((err) => {
					console.log("支付失败", err)
					vm.fyPlayStatus = 'error'
					clearTimeout(vm.queryTimer)
					vm.queryTimer = null
					vm.handlePayResult(PaymentStatusEnum['FAIL'])
					return reject(err)
				})
			}
		},

		async onLoad() {
			const options = this.$Route.query
			this.from = options.from
			this.order_id = options.order_id

			try {
				if (!this.from && !this.order_id) throw '页面参数有误'
				await this.queryPayResult().then((result) => {
					if (result) {
						uni.showToast({
							title: '已支付',
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/order_list/order_list?mode=pay'
							})
						}, 1000)
					}
				})
				await this.initPageData()
				this.loadingSkeleton = false
			} catch (errMsg) {
				this.pageErrorMsg = errMsg
				this.pageStatus = PageStatusEnum['ERROR']
			}
		},

		onShow() {
			// #ifdef H5
			this.$emit('h5_payment')
			// #endif
			// 这里还需要重新判断他的支付方式
			if (this.fyPlayStatus === 'loading') {
				this.handleFY()
			}

		},
		onHide() {
			clearTimeout(this.queryTimer)
			this.queryTimer = null
		},
		beforeDestroy() {
			clearTimeout(this.queryTimer)
			this.queryTimer = null
			this.fyPlayStatus = ''
		},

		onUnload() {
			this.handlePayResult(PaymentStatusEnum['CLOSE'])
		}
	}
</script>

<style lang="scss" scoped>
	.payment-header {
		background-color: #ff584d;
	}

	.footer {
		background-color: #e57d53;
	}

	.payment {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100vh;
		max-height: 100vh;
		padding-bottom: calc(100rpx + 20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + 20rpx + env(safe-area-inset-bottom));

		&-header {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			height: 300rpx;
			@include background_linear(260deg) color: #ffffff;
		}

		&-main {
			flex: 1;
			margin-top: -40rpx;
			padding: 0 20rpx;
			overflow: hidden;
		}

		&-footer {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			align-items: center;
			height: calc(100rpx + constant(safe-area-inset-bottom));
			height: calc(100rpx + env(safe-area-inset-bottom));
			padding: 0 20rpx constant(safe-area-inset-bottom) 20rpx;
			padding: 0 20rpx env(safe-area-inset-bottom) 20rpx;
			background-color: #ffffff;
		}

		.payway-container {
			padding: 0 20rpx;
			border-radius: 7px;
			background-color: #ffffff;

			.payway-empty {
				display: flex;
				justify-content: center;
				padding: 20rpx 0;
				font-size: $-font-size-sm;
				color: $-color-muted;
			}
		}

		.payway {
			width: 100%;

			&-item {
				width: 100%;
				display: flex;
				align-items: center;
				height: 120rpx;

				&:nth-child(n + 2) {
					border-top: $-dashed-border;
				}

				&-content {
					flex: 1;
					display: flex;
					flex-direction: column;
					margin-left: 16rpx;

					&-name {
						font-size: $-font-size-nr;
						color: $-color-black;
					}

					&-tips {
						font-size: $-font-size-xxs;
						color: $-color-muted;
					}
				}
			}
		}

		&-count-down {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 7rpx 25rpx;
			border-radius: 60px;
			margin-top: 10rpx;
			font-size: $-font-size-xxs;
			background-color: #ffffff;
			color: $-color-normal;
		}

		&-submit {
			flex: 1;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 74rpx;
			font-size: $-font-size-nr;
			border-radius: 60px;
			@include background_linear(260deg) color: #ffffff;

			&--disabled::before {
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				height: 100%;
				display: block;
				content: '';
				background: rgba(255, 255, 255, 0.3) !important;
			}
		}

		.Alipay {
			padding: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;

			.btn {
				@include background_color();
				border-radius: 12rpx;
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				color: white;
			}

			.btn1 {
				border-radius: 12rpx;
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				color: white;
			}
		}
	}
</style>